<template>
  <div class="activity-management">
    <h1>志愿者活动管理</h1>

    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.title" placeholder="活动标题" clearable @clear="loadActivities" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.activityType" placeholder="活动类型" clearable @clear="loadActivities">
            <el-option label="监测" :value="1" />
            <el-option label="维护" :value="2" />
            <el-option label="清洁" :value="3" />
            <el-option label="宣传" :value="4" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.auditStatus" placeholder="审核状态" clearable @clear="loadActivities">
            <el-option label="待审核" :value="0" />
            <el-option label="通过" :value="1" />
            <el-option label="拒绝" :value="2" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadActivities">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="activity-list">
      <el-table :data="activities" v-loading="loading" style="width: 100%" border>
        <el-table-column prop="activityId" label="活动ID" width="80" />
        <el-table-column prop="title" label="活动标题" min-width="150" />
        <el-table-column prop="activityType" label="活动类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.activityType === 1">监测</el-tag>
            <el-tag v-else-if="scope.row.activityType === 2" type="success">维护</el-tag>
            <el-tag v-else-if="scope.row.activityType === 3" type="warning">清洁</el-tag>
            <el-tag v-else-if="scope.row.activityType === 4" type="info">宣传</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" min-width="150" />
        <el-table-column prop="startTime" label="开始时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="maxParticipants" label="人数限制" width="100" />
        <el-table-column prop="currentParticipants" label="已报名" width="100" />
        <el-table-column prop="auditStatus" label="审核状态" width="100">

          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 1" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 2" type="danger">拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewActivity(scope.row)">查看</el-button>
            <el-button v-if="scope.row.auditStatus === 0" size="small" type="primary"
              @click="openAuditDialog(scope.row)">
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        style="margin-top: 20px; text-align: right;" />
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="活动详情" width="600px">
      <el-form v-if="currentActivity" :model="currentActivity" label-width="100px" label-position="left">
        <el-form-item label="活动标题">
          <span>{{ currentActivity.title }}</span>
        </el-form-item>
        <el-form-item label="活动图片">
          <el-image v-if="currentActivity.activityImage" :src="currentActivity.activityImage"
            style="width: 200px; height: 150px" fit="cover" />
          <span v-else>无图片</span>
        </el-form-item>
        <el-form-item label="活动类型">
          <el-tag v-if="currentActivity.activityType === 1">监测</el-tag>
          <el-tag v-else-if="currentActivity.activityType === 2" type="success">维护</el-tag>
          <el-tag v-else-if="currentActivity.activityType === 3" type="warning">清洁</el-tag>
          <el-tag v-else-if="currentActivity.activityType === 4" type="info">宣传</el-tag>
        </el-form-item>
        <el-form-item label="活动时间">
          {{ formatDate(currentActivity.startTime) }} 至 {{ formatDate(currentActivity.endTime) }}
        </el-form-item>
        <el-form-item label="活动地点">
          {{ currentActivity.location }}
        </el-form-item>
        <el-form-item label="报名时间">
          {{ formatDate(currentActivity.registrationStartTime) }} 至 {{
            formatDate(currentActivity.registrationEndTime)
          }}
        </el-form-item>
        <el-form-item label="人数限制">
          {{ currentActivity.maxParticipants }} 人 (已报名: {{ currentActivity.currentParticipants }}人)
        </el-form-item>
        <el-form-item label="活动状态">
          <el-tag v-if="currentActivity.status === 1">招募中</el-tag>
          <el-tag v-else-if="currentActivity.status === 2" type="success">进行中</el-tag>
          <el-tag v-else-if="currentActivity.status === 3" type="info">已完成</el-tag>
          <el-tag v-else-if="currentActivity.status === 4" type="danger">已取消</el-tag>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-tag v-if="currentActivity.auditStatus === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="currentActivity.auditStatus === 1" type="success">通过</el-tag>
          <el-tag v-else-if="currentActivity.auditStatus === 2" type="danger">拒绝</el-tag>
        </el-form-item>
        <el-form-item v-if="currentActivity.auditReason" label="审核原因">
          {{ currentActivity.auditReason }}
        </el-form-item>
        <el-form-item v-if="currentActivity.auditTime" label="审核时间">
          {{ formatDate(currentActivity.auditTime) }}
        </el-form-item>
        <el-form-item label="活动描述">
          {{ currentActivity.description || '无描述' }}
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="活动审核" width="500px">
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="100px">
        <el-form-item label="活动标题">
          <span>{{ currentActivity?.title }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditForm.auditStatus === 2" label="审核原因" prop="auditReason">
          <el-input v-model="auditForm.auditReason" type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVoluntaryList, getVoluntaryDetail, auditVoluntary } from '@/apis/voluntaryAPI'

// 数据定义
const activities = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const currentActivity = ref(null)
const auditFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  title: '',
  activityType: null,
  auditStatus: null
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 审核表单
const auditForm = reactive({
  activityId: null,
  auditStatus: 1, // 默认通过
  auditReason: ''
})

// 审核表单验证规则
const auditRules = {
  auditStatus: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  auditReason: [
    { required: true, message: '请输入审核原因', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载活动列表
const loadActivities = async () => {
  loading.value = true
  try {
    // 使用你已经改好的接口
    const result = await getVoluntaryList({
      ...searchForm,
      page: pagination.currentPage,
      size: pagination.pageSize
    })

    activities.value = result.data.records
    pagination.total = result.data.total
  } catch (error) {
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.activityType = null
  searchForm.auditStatus = null
  loadActivities()
}

// 查看活动详情 - 使用单独的详情查询接口
const viewActivity = async (activity) => {
  try {
    const result = await getVoluntaryDetail(activity.activityId)
    if (result.code === 1) {
      currentActivity.value = result.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('加载活动详情失败')
    }
  } catch (error) {
    ElMessage.error('加载活动详情失败')
  }
}

// 打开审核对话框 - 确保有活动详情数据
const openAuditDialog = async (activity) => {
  try {
    // 如果currentActivity还没有数据，或者不是当前活动的数据，则获取详情
    if (!currentActivity.value || currentActivity.value.activityId !== activity.activityId) {
      const result = await getVoluntaryDetail(activity.activityId)
      if (result.code === 1) {
        currentActivity.value = result.data
      } else {
        ElMessage.error('加载活动详情失败')
        return
      }
    }

    // 初始化审核表单
    auditForm.activityId = activity.activityId
    auditForm.auditStatus = 1
    auditForm.auditReason = ''
    auditDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载活动详情失败')
  }
}

// 提交审核 - 使用单独的审核接口
const submitAudit = async () => {
  if (!auditFormRef.value) return

  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const result = await auditVoluntary(auditForm)
        if (result.code === 1) {
          ElMessage.success('审核成功')
          auditDialogVisible.value = false
          loadActivities() // 审核后重新加载列表以更新状态
        } else {
          ElMessage.error(result.message || '审核失败')
        }
      } catch (error) {
        ElMessage.error('审核失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadActivities()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadActivities()
}

// 组件挂载时加载数据
onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.activity-list {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>